package com.example.myone.Activity;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;

import com.example.myone.R;
public class WelcomeActivity extends AppCompatActivity {

    private boolean isMainActivityLoaded = false; // 记录是否已加载MainActivity数据
    private boolean hasStartedMainActivity = false; // 记录是否已启动MainActivity
    private final Handler handler = new Handler(Looper.getMainLooper());
    private ProgressBar progressBar;

    private static final int REQUEST_PERMISSIONS_CODE = 1;
    private static final int MANAGE_EXTERNAL_STORAGE_PERMISSION_REQUEST = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome_activity);
        checkAndRequestPermissions();
        // 初始化 imageView 和 progressBar
        ImageView imageView = findViewById(R.id.image);
        progressBar = findViewById(R.id.progressBar);
        // 设置图片动画
        ViewCompat.animate(imageView)
                .scaleX(1.0f)
                .scaleY(1.0f)
                .setDuration(1000)
                .setListener(new ViewPropertyAnimatorListener() {
                    @Override
                    public void onAnimationStart(@NonNull View view) {
                        // 动画开始时初始化加载 MainActivity 的数据
                        initMainActivityData();
                    }
                    @Override
                    public void onAnimationEnd(@NonNull View view) {
                        // 动画结束时检查是否加载了 MainActivity，并确保只启动一次
                        if (isMainActivityLoaded && !hasStartedMainActivity) {
                            startMainActivity();
                        } else {
                            // 如果未加载完成，显示加载进度并延迟检查
                            progressBar.setVisibility(View.VISIBLE);
                            handler.postDelayed(() -> {
                                if (isMainActivityLoaded && !hasStartedMainActivity) {
                                    progressBar.setVisibility(View.GONE);
                                    startMainActivity();
                                }
                            }, 500); // 延迟500ms再检查一次
                        }
                    }

                    @Override
                    public void onAnimationCancel(@NonNull View view) {
                        // 可处理动画取消时的操作
                    }
                });
    }

    // 启动 MainActivity
    private void startMainActivity() {
        hasStartedMainActivity = true; // 标志位：MainActivity已启动
        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        finish();
    }

    // 模拟加载 MainActivity 数据
    private void initMainActivityData() {
        new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟加载耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 标记 MainActivity 数据加载完成
            isMainActivityLoaded = true;
            // 更新UI
            handler.post(() -> {
                progressBar.setVisibility(View.GONE); // 隐藏进度条
                if (isMainActivityLoaded && !hasStartedMainActivity) {
                    startMainActivity(); // 加载完成后启动MainActivity
                }
            });
        }).start();
    }
    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, MANAGE_EXTERNAL_STORAGE_PERMISSION_REQUEST);
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, REQUEST_PERMISSIONS_CODE);
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS_CODE) {
            if (grantResults.length == 0 || grantResults[0] != PERMISSION_GRANTED) {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "没有权限无法访问", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MANAGE_EXTERNAL_STORAGE_PERMISSION_REQUEST) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (!Environment.isExternalStorageManager()) {
                    // 权限被拒绝，提示用户
                    Toast.makeText(this, "没有权限无法访问", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
